package com.xtianzhuang.www.controller.user.login;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xtianzhuang.www.annotation.Log;
import com.xtianzhuang.www.annotation.Log.LogType;
import com.xtianzhuang.www.controller.BaseController;
import com.xtianzhuang.www.entity.constants.CodeConstants;
import com.xtianzhuang.www.entity.request.LoginRequest;
import com.xtianzhuang.www.entity.request.base.BaseRequest;
import com.xtianzhuang.www.entity.response.LoginResponse;
import com.xtianzhuang.www.entity.response.base.BaseResponse;

/**
 * 
 * @ClassName: LoignController
 * @author : xtian.zhuang
 * @date 2018年6月5日 下午7:01:30
 */
@Controller
@RequestMapping({"/h", "/home"})
public class LoginController extends BaseController {

	@RequestMapping(value = "/login")
	public ModelAndView login(BaseRequest request, BaseResponse response) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("login/index");
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		// 跳回原地址
		return modelAndView;
	}


	/**
	  * 登录
	 * @param request
	 * @param loginRequest
	 * @return
	 */
	@RequestMapping(value = "/doLogin", method = RequestMethod.POST)
	@ResponseBody
	@Log(type = LogType.LOGIN)
	public LoginResponse dologin(HttpServletRequest request, LoginRequest loginRequest) {
		LoginResponse response = new LoginResponse();
		try {
			// 校验登录信息
			userServiceBiz.checkLogin(loginRequest);
			userServiceBiz.doUserLogin(request, loginRequest);
			response.setCode(CodeConstants.SUCCESS);
			response.setMessage("登录成功");
		} catch (Exception e) {
			// TODO: handle exception
			response.setCode(CodeConstants.FAIL);
			response.setMessage(e.getMessage());
		}
		return response;

	}

	/**
	  * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/logout")
	@Log(type = LogType.LOGIN)
	public ModelAndView logout(BaseRequest request, BaseResponse response) {
		// shiro退出登录 login/index
		SecurityUtils.getSubject().logout();
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("login/index");
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		// 跳回原地址
		return modelAndView;
	}
}
